package cn.jfast.expand.wx.api.web;

import cn.jfast.expand.wx.aes.AesException;
import cn.jfast.expand.wx.api.core.WxCore;
import cn.jfast.framework.base.util.Assert;
import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.LogType;
import cn.jfast.framework.log.Logger;
import cn.jfast.framework.web.view.viewtype.Text;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

public abstract class WxWebEntry {
	
	private static final Logger log = LogFactory.getLogger(LogType.JFast,WxWebEntry.class);

    public Text doGet(HttpServletRequest request,
                         HttpServletResponse response,String mpKey) throws ServletException, IOException {
    	Assert.notEmpty(mpKey, "mpKey不可为空");
    	WxCore wxCore = new WxCore(mpKey);
        wxCore.init(request);
        try {
        	log.info("调用微信配置实体:%s", wxCore.getMpAct());
            String echo = wxCore.check();
            if (!echo.isEmpty()) {
                return new Text(echo).setContentType("text/html");
            } else {
            	log.error("微信接入验证URL时失败!!!");
                log.error("微信服务器echoStr值: %s", wxCore.getEchostr());
                log.error("SHA1签名echoStr值: %s", echo);
            	return new Text("error").setContentType("text/html");
            }
        } catch (AesException e) {
            log.error("微信接入验证URL时出现异常!!!");
            log.error(e.getLocalizedMessage(), e);
        }
		return null;
    }

    public Text doPost(HttpServletRequest request,
                          HttpServletResponse response,String mpKey) throws ServletException, IOException {
    	Assert.notEmpty(mpKey, "mpKey不可为空");
    	WxCore wxCore = new WxCore(mpKey);
        wxCore.init(request);
        String result = "error";
        try {
        	log.info("调用微信配置实体:%s", wxCore.getMpAct());
            result = wxCore.handler();
        } catch (Exception e) {
            log.error("解析微信消息时出现异常!!!");
            log.error(e.getLocalizedMessage(), e);
        }
        return new Text(result).setContentType("text/html");
    }

}
